package thread;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingDeque;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 刘远望
 * Date: 2025-06-02
 * Time: 15:48
 */
//实现一个固定线程个数的线程池
class MyThreadPool {

    private BlockingQueue<Runnable> queue = null;
    Thread[] Threads = null;


    public MyThreadPool(int n) {
        //这里使用ArrayBlockingQueue(阻塞队列)作为线程池的队列，容量为1000
        queue = new ArrayBlockingQueue<Runnable>(1000);

        Threads = new Thread[n];

        //初始化线程池，创建n个线程
        for (int i = 0; i < n; i++) {
            Threads[i] = new Thread(() -> {
                while (!Thread.currentThread().isInterrupted()) {
                    try {
                        Runnable task = queue.take();
                        task.run();
                    } catch (InterruptedException e) {
                        Thread.currentThread().interrupt();
                        break;
                    }
                }
            });
            Threads[i].start();
        }

    }

    //提交任务
    public void submit(Runnable task) throws InterruptedException {
        //将任务放入队列中
        queue.put(task);
    }

    //关闭线程池
    public void shutdown() {
        while (!queue.isEmpty()) {
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

        for (Thread thread : Threads) {
            thread.interrupt();
        }

    }
}
public class Demo35 {
    public static void main(String[] args) throws InterruptedException {
        MyThreadPool pool = new MyThreadPool(10);

        for (int i = 0; i < 100; i++) {
            int id = i;
            pool.submit(() -> {
                System.out.println(Thread.currentThread().getName() + " id=" + id);
            });
        }
        //关闭线程池
        pool.shutdown();

    }
}
